import { useState, useCallback } from 'react';
import { message } from 'antd';

// API调用状态接口
export interface ApiCallState<T = any> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

// API调用选项
export interface ApiCallOptions {
  showSuccessMessage?: boolean;
  showErrorMessage?: boolean;
  successMessage?: string;
  errorMessage?: string;
  onSuccess?: (data: any) => void;
  onError?: (error: any) => void;
}

// 通用API调用Hook
export const useApiCall = <T = any>(initialData: T | null = null) => {
  const [state, setState] = useState<ApiCallState<T>>({
    data: initialData,
    loading: false,
    error: null,
  });

  // 执行API调用
  const execute = useCallback(async (
    apiCall: () => Promise<T>,
    options: ApiCallOptions = {}
  ): Promise<T | null> => {
    const {
      showSuccessMessage = false,
      showErrorMessage = true,
      successMessage = '操作成功',
      errorMessage = '操作失败',
      onSuccess,
      onError,
    } = options;

    setState(prev => ({ ...prev, loading: true, error: null }));

    try {
      const result = await apiCall();
      
      setState(prev => ({ 
        ...prev, 
        data: result, 
        loading: false, 
        error: null 
      }));

      if (showSuccessMessage) {
        message.success(successMessage);
      }

      if (onSuccess) {
        onSuccess(result);
      }

      return result;
    } catch (error: any) {
      const errorMsg = error?.message || error?.response?.data?.message || errorMessage;
      
      setState(prev => ({ 
        ...prev, 
        loading: false, 
        error: errorMsg 
      }));

      if (showErrorMessage) {
        message.error(errorMsg);
      }

      if (onError) {
        onError(error);
      }

      return null;
    }
  }, []);

  // 重置状态
  const reset = useCallback(() => {
    setState({
      data: initialData,
      loading: false,
      error: null,
    });
  }, [initialData]);

  // 设置数据
  const setData = useCallback((data: T) => {
    setState(prev => ({ ...prev, data }));
  }, []);

  // 设置加载状态
  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({ ...prev, loading }));
  }, []);

  // 设置错误
  const setError = useCallback((error: string | null) => {
    setState(prev => ({ ...prev, error }));
  }, []);

  return {
    ...state,
    execute,
    reset,
    setData,
    setLoading,
    setError,
  };
};

export default useApiCall;
